import type { RouteRecordRaw } from 'vue-router'
import type { LoginMenu, LoginUserInfo } from '@/apis/common/loginApi'
import type { MenuProps } from '@/components/menu/menu'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { loginApi } from '@/apis/common/loginApi'
import { moduleRoutes } from '@/router/routes'
import { useAppStore } from './appStore'

export const useLoginStore = defineStore('login', () => {
  // 用户信息
  const user = ref<LoginUserInfo>({
    token: localStorage.getItem('store-user-token') ?? undefined,
  })
  // 用户菜单
  const menus = ref<MenuProps[]>([])
  // 资源编码集合
  const resCodes = ref<string[]>([])

  async function loadMenus() {
    if (menus.value.length > 0) {
      return menus.value
    }
    const appStore = useAppStore()
    if (appStore.isRemoteMenu) {
      const data = await loginApi.queryLoginMenus()
      menus.value = resourceToMenus(data)
    }
    else {
      menus.value = routesToMenus(moduleRoutes)
    }
    return menus.value
  }

  /**
   * 转换路由菜单
   */
  function resourceToMenus(resArray?: LoginMenu[]): MenuProps[] {
    const result: MenuProps[] = []
    if (resArray && resArray.length > 0) {
      for (let i = 0; i < resArray.length; i++) {
        const res = resArray[i]
        if (res.code) {
          resCodes.value.push(res.code)
        }
        const children = resourceToMenus(res.children)
        if (res.type === 'MENU') {
          result.push({
            path: res.path!,
            title: res.name!,
            icon: res.icon,
            isHide: !res.visible,
            children,
          })
        }
      }
    }
    return result
  }

  /**
   * 转换路由菜单
   */
  function routesToMenus(routes?: RouteRecordRaw[]): MenuProps[] {
    const result: MenuProps[] = []
    if (routes) {
      for (let i = 0; i < routes.length; i++) {
        const route = routes[i]
        if (route.meta?.title) {
          result.push({
            path: route.path,
            title: route.meta.title,
            icon: route.meta?.icon,
            isHide: route.meta.hide,
            children: routesToMenus(route.children),
          })
        }
        else if (route.children && route.children.length > 0) {
          result.push(...routesToMenus(route.children))
        }
      }
    }
    return result
  }

  function login(u: LoginUserInfo) {
    user.value = u
    if (user.value.token) {
      localStorage.setItem('store-user-token', user.value.token)
    }
  }

  /**
   * @returns 是否登录
   */
  function isLogin() {
    return user.value.token !== undefined
  }

  /**
   * 退出登录
   */
  async function logout() {
    user.value = {}
    menus.value = []
    resCodes.value = []
    localStorage.removeItem('store-user-token')
  }

  /**
   * 加载登录信息
   */
  async function loadLoginInfo() {
    login(await loginApi.getLoginInfo())
  };

  /**
   * 激活菜单
   */
  function activeMenu(path: string) {
    let activeFirstLevel = false
    menus.value.forEach((menu) => {
      setActiveMenu(menu, path)
      if (path === menu.path) {
        activeFirstLevel = true
      }
    })
    if (activeFirstLevel) {
      // 如果菜单只激活第一层，则展开所有第一层
      menus.value.forEach(menu => menu.isOpen = true)
    }
  }

  /**
   * 激活菜单
   */
  function setActiveMenu(menu: MenuProps, path: string) {
    let isActive = path === menu.path
    if (menu.children && menu.children.length > 0) {
      for (let i = 0; i < menu.children.length; i++) {
        const m = menu.children[i]
        if (setActiveMenu(m, path)) {
          isActive = true
        }
      }
      if (isActive) {
        menu.isOpen = isActive
      }
    }
    menu.isActive = isActive
    return isActive
  }

  function hasAuth(authCode?: string) {
    if (authCode !== undefined && authCode.length > 0) {
      return resCodes.value.includes(authCode)
    }
    return true
  }

  return { user, menus, hasAuth, activeMenu, loadMenus, login, isLogin, logout, loadLoginInfo }
})
